package com.htjc.integral.activity.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.htjc.integral.activity.mapper.CouponMapper;
import com.htjc.integral.activity.mapper.EcConsigneeUcExtMapper;
import com.htjc.integral.activity.mapper.EcOrderLotteryMapper;
import com.htjc.integral.activity.mapper.EcPromotionLotteryRecordMapper;
import com.htjc.integral.activity.mapper.FileinfoMapper;
import com.htjc.integral.activity.mapper.IntegralLotteryMapper;
import com.htjc.integral.activity.mapper.StoreDrawMapper;
import com.htjc.integral.activity.service.IIntegralLotteryService;
import com.htjc.integral.activity.util.JsonUtil;
import com.htjc.integral.activity.util.PageVo;
import com.htjc.integral.activity.util.RedisTem;
import com.htjc.integral.activity.util.ResultModel;
import com.htjc.integral.activity.util.SerializeUtil;
import com.htjc.integral.activity.util.UrlConfigUtil;
import com.htjc.integral.activity.util.enums.RedisKey;
import com.htjc.integral.common.annotation.ExecuteTime;
import com.htjc.integral.common.util.RequestUtils;
import com.htjc.integral.common.util.SensitiveDataUtil;
import com.htjc.integral.common.util.TimeUtil;
import com.htjc.integral.common.util.UUIDGenerator;
import com.htjc.integral.model.activity.ChouJiangLiShiTiaoJian;
import com.htjc.integral.model.activity.EcAwardProvinces;
import com.htjc.integral.model.activity.EcConsignee;
import com.htjc.integral.model.activity.EcCouponRecord;
import com.htjc.integral.model.activity.EcOrderLottery;
import com.htjc.integral.model.activity.EcPromotion;
import com.htjc.integral.model.activity.EcPromotionAwardSetting;
import com.htjc.integral.model.activity.EcPromotionLotteryRecord;
import com.htjc.integral.model.activity.EcPromotionParamValue;
import com.htjc.integral.model.activity.EsgccDbuser;
import com.htjc.integral.model.activity.Fileinfo;
import com.htjc.integral.model.activity.SignDetail;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "jfLog")
@Service
/**
 * 抽奖的业务层接口
 * @author zw
 *
 */
public class IntegralLotteryServiceImpl implements IIntegralLotteryService{
	@Autowired
	private IntegralLotteryMapper integralLotteryMapper;

	@Autowired
	private EcOrderLotteryMapper ecOrderLotteryMapper;
	@Autowired
	private UrlConfigUtil urlConfigUtil;
	@Autowired
	private FileinfoMapper fileinfoMapper;
	@Autowired
	private StoreDrawMapper storeDrawMapperK;
	@Autowired
	private RedisTem redisTem;
	@Autowired
	private CouponMapper  couponMapper;
	@Autowired
	private EcConsigneeUcExtMapper ecConsigneeUcExtMapper;
	@Autowired
	private EcPromotionLotteryRecordMapper ecPromotionLotteryRecordMapper;

	/**
	 * 积分抽奖首页
	 *
	 * @param  json(promotionId:活动id,userId：用户id,userName)
	 * @return json字符串
	 *
	 * 问题：抽奖初始化显示奖品，奖品图片问题暂时为处理
	 */
	@SuppressWarnings("unused")
	@ExecuteTime
	@Override
	public JSONObject init(JSONObject json) {
		//活动id
		String promotionId = null;
		String userId = null;
		//统一用户中心接口地址
		String USERCENTER_URL = urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.USER_CENTER_QUERY.getKey());
		if (json.containsKey("PROMOTION_ID")) {
			promotionId = json.getString("PROMOTION_ID");
		}
		if (json.containsKey("USER_ID")) {
			userId = json.getString("USER_ID");
		}
		JSONObject result = new JSONObject();

		log.info("活动ID========="+promotionId);
		log.info("查询促销活动实例表信息=============》开始《===========");
		EcPromotion ecPromotion = integralLotteryMapper.getEcPromotionById(promotionId);
		//		EcPromotion ecPromotion = new EcPromotion();
		//		ecPromotion.setPromotionId("111");
		//		ecPromotion.setEnwhitelist("111");
		log.info("查询促销活动实例表信息=============》结束《===========返回值：{}",ecPromotion);
		//		logger.info("查询到的活动========="+ecPromotion);
		// 1.判断是否存在活动。
		if (ecPromotion != null) {
			if (ecPromotion.getEnwhitelist() != null && !ecPromotion.getEnwhitelist().equals("")) {
				result.put("enwhitelist", ecPromotion.getEnwhitelist());
			} else {
				result.put("enwhitelist", "");
			}
			result.put("promotionId", ecPromotion.getPromotionId());
			String promotionRuledesc="";
			try {
				promotionRuledesc = ecPromotion.getPromotionRuledesc();
			} catch (Exception e) {
				e.printStackTrace();
			}
			result.put("promotionRuledesc", promotionRuledesc);
			// 2.取得抽奖奖品
			log.info("查询抽奖奖品=============》开始《===========");
			List<EcPromotionAwardSetting> epasList = integralLotteryMapper
					.getEcPromotionAwardSettingList(promotionId);
			log.info("查询抽奖奖品=============》结束《===========返回值:{}",epasList);
			//			String userId = TokenUtil.getInstance(redisManager).getUserIdByToken(token);
			BigDecimal lotteryNum = new  BigDecimal("0");
			if (StringUtils.isNotEmpty(userId)){

				String provinceId = "";
				String cityId = "";
				String resultJson="";
				try {
					log.info("查询统一用户返回的绑定用户信息=============》开始《===========");
					//resultJson = integralLotteryService.chaxunBound(userId);
					// 调用统一用户中心接口的应答域
					//resultJson = RequestUtils.sendPost(USERCENTER_URL, unionJson.toString());
					//					resultJson = "{'SRVRT':'0000','RESULTMESSAGE':'返回成功','RESULTCODE':'0000','TIMESTAMP':'11232165446','TIMESTAMP':'POWERUSERLIST',"
					//							+ "'BIZRT':{'POWERUSERLIST':[{'ORGNO':'3110201','PROVINCEID':'31102','ELECTYPECODE':'01','PRONO':'12345','BINDTYPE':'2','CONSNO':'120123123'},"
					//							+ "{'ORGNO':'3110201','PROVINCEID':'31102','ELECTYPECODE':'01','PRONO':'12346','BINDTYPE':'2','CONSNO':'120123124'}]}}";
					resultJson = "{'SRVRT':'0000','RESULTMESSAGE':'返回成功','RESULTCODE':'0000','TIMESTAMP':'11232165446','TIMESTAMP':'POWERUSERLIST',"
							+ "'BIZRT':{'POWERUSERLIST':[{'ORGNO':'3110201','PROVINCEID':'31102','ELECTYPECODE':'01','PRONO':'12345','BINDTYPE':'2','CONSNO':'120123123','POWERUNIT':'11111'},"
							+ "{'ORGNO':'3110201','PROVINCEID':'410000','ELECTYPECODE':'01','PRONO':'12346','BINDTYPE':'2','CONSNO':'120123124','POWERUNIT':'41401'}]}}";
					log.info("查询统一用户返回的绑定用户信息=============》结束《===========");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				log.info("统一用户返回的绑定用户信息=========>{}",resultJson);
				if(resultJson!=null && !resultJson.equals("")){
					if(StringUtils.equals("0000", JSONObject.parseObject(resultJson).getString("SRVRT"))){
						String retVal = JSONObject.parseObject(resultJson).getJSONObject("BIZRT").getString("POWERUSERLIST");
						if(StringUtils.isNotBlank(retVal) && (!"[]".equals(retVal))){
							JSONArray jsonArray = JSONObject.parseObject(resultJson).getJSONObject("BIZRT").getJSONArray("POWERUSERLIST");
							if(jsonArray != null){//账号绑定用户信息
								for (int i = 0; i < jsonArray.size(); i++) {
									JSONObject jaList = (JSONObject) jsonArray.get(i);  //取绑定信息的第一条记录
									if(jaList != null){
										log.info("统一用户返回的绑定用户信息的用电单位编号========={}"+jaList);
										String powerUnit = jaList.getString("POWERUNIT");  	//供电公司编号
										provinceId = jaList.getString("PROVINCEID");  //网省编号
										log.info("统一用户返回的绑定用户信息的用电单位编号========="+powerUnit);
										if(powerUnit.length() >= 5){
											cityId = powerUnit.substring(0,5);
											log.info("用户绑定城市ID========="+cityId);
										}
										Map<String, String> awardProvincesparam = new HashMap<String, String>();
										awardProvincesparam.put("promotionId",ecPromotion.getPromotionId());
										awardProvincesparam.put("provinceId",provinceId);
										awardProvincesparam.put("cityId",cityId);
										log.info("查询当前用户供电公司是否在抽奖 地市范围内=============》开始《===========");
										List<EcAwardProvinces> ecAwardProvincesList = integralLotteryMapper.selectEcAwardProvinces(awardProvincesparam);
										log.info("查询当前用户供电公司是否在抽奖 地市范围内=============》结束《===========返回值:{}",ecAwardProvincesList);
										if (ecAwardProvincesList != null && !ecAwardProvincesList.isEmpty()) {
											String qsflag = ecAwardProvincesList.get(0).getFlag();
											log.info("全省抽奖还是地市抽奖qsflag========="+qsflag);
											// 抽奖逻辑
											//如果flag=="2"不是全省抽奖
											if(qsflag.equals("2")){
												Map<String, String> param = new HashMap<String, String>();
												param.put("promotionId",ecPromotion.getPromotionId());
												param.put("cityId",cityId);
												log.info("抽奖奖品设置信息(按照地市查询奖池)=============》开始《===========");
												epasList = integralLotteryMapper.getEcPromotionAwardSettingListCity(param);
												log.info("抽奖奖品设置信息(按照地市查询奖池)=============》结束《===========返回值:{}",epasList);
											}
											break;
										}
										else continue;
									}
								}
							}
						}
					}
				}

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("partnerId", userId);
				map.put("promotionId", promotionId);
				log.info("查询抽奖订单=============》开始《===========");
				List<EcOrderLottery> list = ecOrderLotteryMapper.selectByPartnerId(map);
				log.info("查询抽奖订单=============》结束《===========返回值{}",list);
				if(list!=null&&list.size()>0){
					EcOrderLottery ecOrderLottery = list.get(0);
					lotteryNum = ecOrderLottery.getLotteryNum();
				}
			}

			for (EcPromotionAwardSetting epas : epasList) {
				epas.setWinningType(epas.getWinningType().trim());
				if (epas.getWinningType().equals("2") && epas.getPrizes() == null) {
					integralLotteryMapper.updateEcPromotionAwardSetting(ecPromotion.getPromotionId());
				}
				if (epas.getImgID() != null && !epas.getImgID().equals("")) {
					if (fileinfoMapper.selectByBuzId(epas.getImgID()) == null
							|| fileinfoMapper.selectByBuzId(epas.getImgID()).size() == 0) {
						log.info("图片地址读取===================》fileinfoMapper查询为空");
						epas.setImgID("");

					} else {
						Fileinfo fileInfo = fileinfoMapper.selectByBuzId(epas.getImgID()).get(0);
						log.info("图片地址读取===================》fileinfoMapper查询存在");
						String IMG_URL = urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.IMG_URLADD.getKey());// "http://images.esgmallt.com";//
						log.info("图片地址读取===================》fileInfo{}",fileInfo.getRelapath());
						if (fileInfo != null) {
							//String imageMirrorPaths = ImageUtils.getInstance().getImageMirrorPaths(fileBrowserUrl);
							String imgUrl = IMG_URL + fileInfo.getRelapath() + fileInfo.getFileaname();
							log.info("图片地址读取===================》imgUrl{}",imgUrl);
							epas.setImgID(imgUrl);
						} else {
							epas.setImgID("");
						}
					}
				} else {
					epas.setImgID("");
				}
			}
			result.put("epasList", epasList);
			result.put("epasListLength", epasList.size());

			// 3.得到以前抽奖记录(当周所有的中奖记录)
			ChouJiangLiShiTiaoJian cjlt = new ChouJiangLiShiTiaoJian();
			cjlt.setPromotionId(promotionId);
			log.info("得到以前抽奖记录(当周所有的中奖记录)======================》开始《================");
			List<EcPromotionLotteryRecord> eplrList = integralLotteryMapper
					.getEcPromotionLotteryRecordList(cjlt);
			log.info("得到以前抽奖记录(当周所有的中奖记录)======================》结束《================返回值{}",eplrList);
			for (EcPromotionLotteryRecord eplr : eplrList) {
//				//新账户体系无个人信息
					eplr.setLotteryAccount(SensitiveDataUtil.toConceal(eplr.getUserName()));
			}
			result.put("eplrList", eplrList);

			// 4.得到（每日免费抽奖次数，单次抽奖积分扣除数，积分投入数）
			List<EcPromotionParamValue> eppvList = integralLotteryMapper
					.getEcPromotionParamValueList(promotionId);

			BigDecimal strTemp = new BigDecimal("0");
			for (EcPromotionParamValue eppv : eppvList) {
				if (eppv.getPromotionParamId().equals("PROM_INTEGRAL_DRAW_PRAM_00")) {
					int compareTo = lotteryNum.compareTo(strTemp);
					//					logger.info("免费次数============="+lotteryNum);
					//					logger.info("比较大小============="+compareTo);
					if(compareTo==1){
						//						logger.info("免费次数比较大小============="+compareTo);
						result.put("mfcs", lotteryNum.intValue()+"");
					}else{
						//						logger.info("比较大小============="+compareTo);
						result.put("mfcs", eppv.getPromotionParamValue());
					}
				} else if (eppv.getPromotionParamId().equals("PROM_INTEGRAL_DRAW_PRAM_01")) {
					result.put("kcfs", eppv.getPromotionParamValue());
				} else if (eppv.getPromotionParamId().equals("PROM_INTEGRAL_DRAW_PRAM_02")) {
					result.put("jftrs", eppv.getPromotionParamValue());
				}
			}
			result.put("rcode", "0");
			result.put("resultMsg", "接口调用成功");
		} else {
			result.put("rcode", "1");
			result.put("resultMsg", "对不起，活动尚未开始，敬请期待！");
		}

		//		logger.info("KK测试开始----------------------------------------");
		log.info("获取首页返回值为result:" + result.toString());
		//		logger.info("KK测试结束----------------------------------------");

		return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.ActivityReturnSucceed(result)));
	}
	/**
	 * 点击抽奖前，进行抽奖检查
	 * @param (promotionId:活动id,userId：用户id)
	 *
	 * 资格抽奖 是否有用户当日抽奖次数、积分 活动是否结束 用户当日抽奖次数
	 * 问题：暂时无用户信息需添加？，白名单暂时无效需添加？
	 */
	public JSONObject getLotteryCheck(JSONObject param) {
		JSONObject result = new JSONObject();
		//统一用户中心接口地址
		//		String USERCENTER_URL = urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.USER_CENTER_QUERY.getKey());

		String promotionId = null;
		String enwhitelist = null;
		String userId = param.getString("UNION_ID");

		if (StringUtils.isBlank(param.getString("UNION_ID"))) {
			result.put("rcode", "1204");
			result.put("resultMsg", "用户未登录");
		}

		else {

			if (param.containsKey("PROMOTION_ID")) {
				promotionId = param.getString("PROMOTION_ID");
			}
			if (param.containsKey("ENWHITELIST")) {
				enwhitelist = param.getString("ENWHITELIST");
			}

			//暂时无用户信息需添加？，白名单暂时无效需添加？
			//			// 获取用户抽奖资格
			//			String qualification = integralLotteryService.getEnwhitelistME(userId, promotionId, enwhitelist);
			result.put("qualification", promotionId);

			// 是否有可扣除单次抽奖积分
			boolean flag = shifoukouchujifenS(userId, promotionId);
			result.put("flag", flag);

			// 活动是否继续开展
			EcPromotion ecPromotion = integralLotteryMapper.getEcPromotionById(promotionId);
			EcPromotionAwardSetting epas = new EcPromotionAwardSetting();
			if (ecPromotion == null) {
				// 活动已结束
				result.put("activityStatus", "11");
			} else if (!ecPromotion.getPromotionId().equals(promotionId)) {
				// 活动已变更
				result.put("activityStatus", "12");
			} else if(ecPromotion.getIsLimitRegion().equals("01")){
				//01是选择省份抽奖
				//				logger.info("用户信息========="+userId);
				String provinceId = "";
				String cityId = "";
				String resultJson="";
				try {
					//resultJson = integralLotteryService.chaxunBound(userId);
					// 调用统一用户中心接口的应答域
					//resultJson = RequestUtils.sendPost(USERCENTER_URL, unionJson.toString());
					//					resultJson = "{'SRVRT':'0000','RESULTMESSAGE':'返回成功','RESULTCODE':'0000','TIMESTAMP':'11232165446','TIMESTAMP':'POWERUSERLIST',"
					//							+ "'BIZRT':{'POWERUSERLIST':[{'ORGNO':'3110201','PROVINCEID':'31102','ELECTYPECODE':'01','PRONO':'12345','BINDTYPE':'2','CONSNO':'120123123'},"
					//							+ "{'ORGNO':'3110201','PROVINCEID':'31102','ELECTYPECODE':'01','PRONO':'12346','BINDTYPE':'2','CONSNO':'120123124'}]}}";
					resultJson = "{'SRVRT':'0000','RESULTMESSAGE':'返回成功','RESULTCODE':'0000','TIMESTAMP':'11232165446','TIMESTAMP':'POWERUSERLIST',"
							+ "'BIZRT':{'POWERUSERLIST':[{'ORGNO':'410000','PROVINCEID':'41401','ELECTYPECODE':'01','PRONO':'12345','BINDTYPE':'2','CONSNO':'120123123','POWERUNIT':'11111'},"
							+ "{'ORGNO':'410000','PROVINCEID':'41401','ELECTYPECODE':'01','PRONO':'12346','BINDTYPE':'2','CONSNO':'120123124','POWERUNIT':'11111'}]}}";
					//					resultJson = integralLotteryService.chaxunBound(userId);
				} catch (Exception e) {
					// 电e宝返回失败
					result.put("activityStatus", "16");
					e.printStackTrace();
				}

				log.info("统一用户返回的绑定用户信息========="+resultJson);
				if(resultJson!=null && !resultJson.equals("")){
					if(StringUtils.equals("0000", JSONObject.parseObject(resultJson).getString("SRVRT"))){
						String retVal = JSONObject.parseObject(resultJson).getJSONObject("BIZRT").getString("POWERUSERLIST");
						if(StringUtils.isNotBlank(retVal) && (!"[]".equals(retVal))){
							JSONArray jsonArray = JSONArray.parseObject(resultJson).getJSONObject("BIZRT").getJSONArray("POWERUSERLIST");
							log.info("powerUserList========="+jsonArray.toString());
							if(jsonArray != null && !"".equals(jsonArray.toString())){//账号绑定用户信息
								for(int i = 0; i < jsonArray.size(); i++){
									JSONObject jaList = (JSONObject) jsonArray.get(i);  //取绑定信息的第一条记录
									if(jaList != null){
										String powerUnit = jaList.getString("POWERUNIT");  	//供电公司编号
										provinceId = jaList.getString("PROVINCEID");  //网省编号
										log.info("统一用户返回的绑定用户信息的用第========="+i+"，用电单位编号========="+powerUnit);
										if(powerUnit.length() >= 5){
											cityId = powerUnit.substring(0,5);
											log.info("用户绑定城市ID========="+cityId);
										}
									}
									Map<String, String> awardProvincesparam = new HashMap<String, String>();
									awardProvincesparam.put("promotionId",ecPromotion.getPromotionId());
									awardProvincesparam.put("provinceId",provinceId);
									awardProvincesparam.put("cityId",cityId);
									List<EcAwardProvinces> ecAwardProvincesList = integralLotteryMapper.selectEcAwardProvinces(awardProvincesparam);
									//					         	logger.info("查询是否在抽奖范围内========="+ecAwardProvincesList);
									if(ecAwardProvincesList == null||ecAwardProvincesList.size() == 0){//判断在不在抽奖范围内
										result.put("activityStatus", "15");//
										continue;
									}
									else{
										//账号绑定用电信息
										result.put("activityStatus", "10");
										break;
									}
								}
							}else {
								//账号未绑定用电信息
								result.put("activityStatus", "13");
							}
						}else {
							//账号未绑定用电信息
							result.put("activityStatus", "13");
						}
					}else {
						result.put("activityStatus", "13");
					}
				}else {
					result.put("activityStatus", "16");
				}

			}
			else {
				// 成功可以调用
				result.put("activityStatus", "10");
			}

			BigDecimal lotteryNum = new BigDecimal("0");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("partnerId", userId);
			map.put("promotionId", promotionId);
			List<EcOrderLottery> list = ecOrderLotteryMapper.selectByPartnerId(map);
			if(list!=null&&list.size()>0){
				EcOrderLottery ecOrderLottery = list.get(0);
				lotteryNum = ecOrderLottery.getLotteryNum();
			}
			BigDecimal strTemp = new BigDecimal("0");
			int compareTo = lotteryNum.compareTo(strTemp);
			if(compareTo==1){
				result.put("LotteryNumber", 0);
			}else{
				// 用户当日抽奖次数
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("promotionId", promotionId);
				paramMap.put("partnerId", userId);
				String LotteryNumber =String.valueOf(integralLotteryMapper.yichoujiangcishu(paramMap));
				result.put("LotteryNumber", LotteryNumber);
			}

			result.put("rcode", "0");
			result.put("resultMsg", "接口调用成功");
		}

		//		return ResponseUtil.formatResponseByRequest(jsonpCallback, result.toString());
		return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.ActivityReturnSucceed(result)));
	}
	/**
	 * 抽奖
	 *
	 * @param json(promotionId:活动id,userId：用户id)
	 * @return
	 * @throws Exception
	 * 问题：原有扣减积分操作注释掉，   是否是调用账户积分余额修改接口？？？？？？
	 *    抽中奖后给用户发送短信方法为沿用以前的放到 注释掉了？？
	 *    电费小红包暂时有问题暂时电费小红包的已注释
	 * 
	 */
	@Override
	public JSONObject drawLottery(JSONObject param) throws Exception {
		log.info("抽奖开始：===============》开始《==============入参{}", param);
		JSONObject result = new JSONObject();
		//资产中心账户积分扣减
		//		String ZCZX_INTEGRAL_DEDUCTION = urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.ZCZX_INTEGRAL_DEDUCTION.getKey());
		//		JSONObject param = JSONObject.parseObject(jsonStr);
		try {
			//验证用户是否登陆
			String userId = param.getString("UNION_ID");
			String provinceId = "";
			String cityId = "";
			if (param.containsKey("UNION_ID")) {
				if (StringUtils.isBlank(userId)) {
					result.put("rcode", "1204");
					result.put("resultMsg", "用户未登录");
					return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.ActivityReturnError(result)));
					//return ResponseUtil.formatResponseByRequest(jsonpCallback, result.toString());
				}
			}

			String promotionId = "";
			if (param.containsKey("PROMOTION_ID")) {
				promotionId = param.getString("PROMOTION_ID");
			}
			//			logger.info("抽奖活动id："+ promotionId);

			//获取抽奖活动
			EcPromotion ecPromotion = integralLotteryMapper.getEcPromotionById(promotionId);
			if (ecPromotion == null) {
				result.put("rcode", "11");
				result.put("resultMsg", "活动已经取消");
				return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.ActivityReturnError(result)));
				//				return ResponseUtil.formatResponseByRequest(jsonpCallback, result.toString());
			}
			if (!ecPromotion.getPromotionId().equals(promotionId)) {
				result.put("rcode", "12");
				result.put("resultMsg", "活动已经变更");
				return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.ActivityReturnError(result)));
				//				return ResponseUtil.formatResponseByRequest(jsonpCallback, result.toString());
			}
			log.info("ecPromotion返回值==================》{}",ecPromotion.getIsLimitRegion());
			if(ecPromotion.getIsLimitRegion().equals("01")){//01是选择省份抽奖
				List<EcAwardProvinces> ecAwardProvincesList = null;
				log.info("查询统一用户返回的绑定用户信息=============》开始《===========");
				//resultJson = integralLotteryService.chaxunBound(userId);
				// 调用统一用户中心接口的应答域
				//resultJson = RequestUtils.sendPost(USERCENTER_URL, unionJson.toString());
				//					resultJson = "{'SRVRT':'0000','RESULTMESSAGE':'返回成功','RESULTCODE':'0000','TIMESTAMP':'11232165446','TIMESTAMP':'POWERUSERLIST',"
				//							+ "'BIZRT':{'POWERUSERLIST':[{'ORGNO':'3110201','PROVINCEID':'31102','ELECTYPECODE':'01','PRONO':'12345','BINDTYPE':'2','CONSNO':'120123123'},"
				//							+ "{'ORGNO':'3110201','PROVINCEID':'31102','ELECTYPECODE':'01','PRONO':'12346','BINDTYPE':'2','CONSNO':'120123124'}]}}";
				String resultJson = "{'SRVRT':'0000','RESULTMESSAGE':'返回成功','RESULTCODE':'0000','TIMESTAMP':'11232165446','TIMESTAMP':'POWERUSERLIST',"
						+ "'BIZRT':{'POWERUSERLIST':[{'ORGNO':'3110201','PROVINCEID':'31102','ELECTYPECODE':'01','PRONO':'12345','BINDTYPE':'2','CONSNO':'120123123','POWERUNIT':'11111'},"
						+ "{'ORGNO':'3110201','PROVINCEID':'410000','ELECTYPECODE':'01','PRONO':'12346','BINDTYPE':'2','CONSNO':'120123124','POWERUNIT':'41401'}]}}";
				log.info("查询统一用户返回的绑定用户信息=============》结束《===========");
				if(resultJson!=null && !resultJson.equals("")){
					if(StringUtils.equals("0000", JSONObject.parseObject(resultJson).getString("SRVRT"))){
						String retVal = JSONObject.parseObject(resultJson).getJSONObject("BIZRT").getString("POWERUSERLIST");
						if(StringUtils.isNotBlank(retVal) && (!"[]".equals(retVal))){
							JSONArray jsonArray = JSONArray.parseObject(resultJson).getJSONObject("BIZRT").getJSONArray("POWERUSERLIST");
							if(jsonArray != null){
								for (int i = 0; i < jsonArray.size(); i++) {
									JSONObject jaList = (JSONObject) jsonArray.get(i);  //取绑定信息的第一条记录
									if(jaList != null){
										String powerUnit = jaList.getString("POWERUNIT");  	//供电公司编号
										provinceId = jaList.getString("PROVINCEID");  //网省编号
										log.info("统一用户返回的绑定用户信息的用电单位编号========="+powerUnit);
										if(powerUnit.length() >= 5){
											cityId = powerUnit.substring(0,5);
											log.info("用户绑定城市ID========="+cityId);
										}
									}
									Map<String, String> awardProvincesparam = new HashMap<String, String>();
									awardProvincesparam.put("promotionId",ecPromotion.getPromotionId());
									awardProvincesparam.put("provinceId",provinceId);
									awardProvincesparam.put("cityId",cityId);
									log.info("查询当前用户供电公司是否在抽奖 地市范围内=============》开始《===========");
									ecAwardProvincesList = integralLotteryMapper.selectEcAwardProvinces(awardProvincesparam);
									log.info("查询当前用户供电公司是否在抽奖 地市范围内=============》结束《===========返回值:{}",ecAwardProvincesList);
									//ecAwardProvincesList = integralLotteryMapper.selectEcAwardProvinces(promotionId,provinceId,cityId);
									if (ecAwardProvincesList != null && !ecAwardProvincesList.isEmpty()) {
										break;
									}
									else continue;
								}
							}
						}
					}
				}

				if (ecAwardProvincesList != null) {
					EcPromotionAwardSetting epas;
					String qsflag = ecAwardProvincesList.get(0).getFlag();
					log.info("全省抽奖还是地市抽奖qsflag========="+qsflag);
					// 抽奖逻辑
					//如果flag=="1"是全省抽奖
					if(qsflag.equals("1")){
						epas = getEcPromotionAwardSetting(promotionId);
					}else{
						epas = getEcPromotionAwardSettingCity(promotionId,cityId);
					}
					List<EcPromotionParamValue> eppvList = integralLotteryMapper.getEcPromotionParamValueList(promotionId);


					String deductedPoints = "0";//抽奖活动单次抽奖扣除积分数
					String freeTimes = "0";//每日免费抽奖次数
					for (EcPromotionParamValue eppv : eppvList) {
						if (eppv.getPromotionParamId().equals("PROM_INTEGRAL_DRAW_PRAM_00")) {
							freeTimes = eppv.getPromotionParamValue();
						} else if (eppv.getPromotionParamId().equals("PROM_INTEGRAL_DRAW_PRAM_01")) {
							deductedPoints = eppv.getPromotionParamValue();
						}
					}
					Map<String, Object> paramMap = new HashMap<String, Object>();
					paramMap.put("promotionId", promotionId);
					paramMap.put("partnerId", userId);
					//用户当日已抽奖次数
					String userLotteryTimes =  String.valueOf(integralLotteryMapper.yichoujiangcishu(paramMap).size());
					String userDeductedPoints = "0";//用户每次抽奖扣除积分数
					String koufen = "0";
					String lotteryRecordId = UUIDGenerator.getInstance().getReplaceUUID();
					//用户免费抽奖次数用完时
					if (Integer.valueOf(userLotteryTimes) >= Integer.valueOf(freeTimes)) {
						boolean flag = shifoukouchujifenS(userId, promotionId);
						if (flag) {
							koufen = deductedPoints;
							JSONObject jsonObject = new JSONObject();
							jsonObject.put("ACCOUNT_NAME", param.getString("TELPHONE"));
							jsonObject.put("LOGIN_ACCOUNT_ID", userId);
							jsonObject.put("BUSINESS_ID",UUIDGenerator.getInstance().getReplaceNotMd5UUID());
							jsonObject.put("OPERATION_STATUS","01");
							jsonObject.put("EXPENDITURE_WHERE", "01");
							jsonObject.put("EXPENDITURE_DESCRIBE", "积分抽奖扣减积分");
							jsonObject.put("EXPENDITURE_NUM", koufen);
							jsonObject.put("WHEREABOUTS_ID", null);
							String resultStr=deductionIntegral(jsonObject.toString());
							if(resultStr.indexOf("成功") == -1){
								log.info("资产中心扣减异常{}",resultStr);
								result.put("rcode", "14");
								result.put("resultMsg", "系统异常");
								return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.ActivityReturnError(result)));
								//								return ResponseUtil.formatResponseByRequest(jsonpCallback, result.toString());
							}
						}else {
							result.put("rcode", "14");
							result.put("resultMsg", "积分不足，抽奖失败");
							return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.ActivityReturnError(result)));
							//							return ResponseUtil.formatResponseByRequest(jsonpCallback, result.toString());
						}
					}

					String mianzhi = "";
					String resultMsg = "";
					// 抽中奖后
					if (!epas.getWinningType().trim().equals("2")) {
						log.info("发送短信功能暂时注释=======================》电话{}",param.getString("TELPHONE"));
						//						Map<String, String> paramMap = new LinkedHashMap<String, String>();
						//						String provinceName = iIntegralLotteryMapper.getProvinceName(provinceId);//查询网省名称
						//						String telMessage = "";
						//						String tel = integralLotteryService.getTelPhone(userId);
						//						log.info("获取的手机号===="+tel+provinceName);
						if (epas.getWinningType().trim().equals("0")) {// 积分
							resultMsg = "获得积分成功";
							//							telMessage ="【"+provinceName+"】尊敬的"+tel+"，您好，感谢您参加"+provinceName+"公司“积分抽大奖活动”,恭喜您抽中"+epas.getPrizes()+"积分，请登陆电e宝,进入积分e+查看，奖励将于三个工作日内到账。如有疑问，请致电（010-95598-1-8），感谢您对"+provinceName+"的关注！";
							// 去除中文
							Matcher mat = Pattern.compile("[\u4e00-\u9fa5]").matcher(epas.getPrizes());
							String Prizes= mat.replaceAll("").toString();
							chouzhongjiang(
									userId, promotionId,
									Prizes,lotteryRecordId);
						} else if (epas.getWinningType().trim().equals("1")) {// 礼券
							resultMsg = "获得礼券成功";
							//							telMessage ="【"+provinceName+"】尊敬的"+tel+"，您好，感谢您参加"+provinceName+"公司“积分抽大奖活动”,恭喜您抽中"+epas.getPrizes()+"元礼券，请登国网商城，进入我的商城，点击优惠券管理查看，奖励将于三个工作日内到账。如有疑问，请致电（010-95598-1-8），感谢您对"+provinceName+"的关注！";
							String code = sendCoupon(
									userId, epas.getPrizes());
							EcCouponRecord ecCouponRecord = couponMapper
									.getEcCouponRecord(code);
							mianzhi = String.valueOf(ecCouponRecord
									.getDenominationAmount());
							epas.setPrizes(mianzhi);
						} else if (epas.getWinningType().trim().equals("3")) {
							resultMsg = "获得实物成功";
							//							telMessage ="【"+provinceName+"】尊敬的"+tel+"，您好，感谢您参加"+provinceName+"公司“积分抽大奖活动”,恭喜您抽中"+epas.getPrizes()+"大奖，我们将在7-15个工作日内完成奖品发放，如有疑问，请致电（010-95598-1-8），感谢您对"+provinceName+"的关注！";
						}else if (epas.getWinningType().trim().equals("4")) {
							resultMsg = "获得电费红包成功";
							//							telMessage ="【"+provinceName+"】尊敬的"+tel+"，您好，感谢您参加"+provinceName+"公司“积分抽大奖活动”,恭喜您抽中"+epas.getPrizes()+"元小红包，请登陆电e宝,进入我的卡包查看，奖励将于三个工作日内到账。如有疑问，请致电（010-95598-1-8），感谢您对"+provinceName+"的关注！";
						}
						epas.setLotteryRecordId(lotteryRecordId);
						//						if(tel!=null && !tel.equals("")){
						//							paramMap.put(ISmsService.SMS_MOBILE, tel);
						//							paramMap.put(ISmsService.SMS_SEND_MESSAGE,
						//									java.net .URLEncoder.encode(telMessage, "utf-8"));
						//							logger.info("发送短信开始"+paramMap);
						//							iSmsEventService.sendSmsEvent(com.alibaba.fastjson.JSON.toJSONString(paramMap));
						//							logger.info("发送短信结束：[手机号"+tel);
						//						}
					}
					else{
						resultMsg = "未抽中，谢谢参与";
					}
					result.put("rcode", "10");
					result.put("resultMsg", resultMsg);
					result.put("epas", epas);

					// 增加抽奖记录
					EcPromotionLotteryRecord eplr = new EcPromotionLotteryRecord();
					eplr.setLotteryRecordId(lotteryRecordId);
					eplr.setPromotionId(promotionId);
					eplr.setLotteryAccount(userId);
					eplr.setUseIntegral(Double.valueOf(userDeductedPoints));
					eplr.setWinningType(epas.getWinningType().trim());
					eplr.setPrizes(epas.getPrizes());
					eplr.setWinningPrice("");
					eplr.setStates("");
					if (epas.getWinningType().trim().equals("0")) {//积分
						// 去除中文
						Matcher mat = Pattern.compile("[\u4e00-\u9fa5]").matcher(eplr.getPrizes());
						Double ss= Double.valueOf(mat.replaceAll(""))*0.005;
						eplr.setWinningPrice(String.valueOf(ss));
					}
					if (epas.getWinningType().trim().equals("1")) {//礼券
						eplr.setPrizes(mianzhi);
						eplr.setWinningPrice(mianzhi);
					}
					if (epas.getWinningType().trim().equals("4")) {//电费红包
						eplr.setStates("1");//派发中
					}
					eplr.setAwardSettingId(epas.getAwardSettingId());
					eplr.setLotteryTime(new Date());
					eplr.setLotterySourec("3");
					eplr.setProvinceId(provinceId);
					eplr.setCityId(cityId);
					eplr.setUserName(param.getString("USER_NAME"));
					log.info("添加抽奖记录==================》开始《=================");
					integralLotteryMapper.insertEcPromotionLotteryRecord(eplr);
					log.info("添加抽奖记录==================》结束《=================");

					if (epas.getWinningType().trim().equals("4")) {// 电费红包
						Map<String, Object> paramMap1 = new HashMap<String, Object>();
						paramMap1.put("promotionId", promotionId);
						paramMap1.put("partnerId", userId);
						List<EcPromotionLotteryRecord> eplrListS = integralLotteryMapper
								.yichoujiangcishu(paramMap1);
						EsgccDbuser esgccDbuser=new EsgccDbuser();
						esgccDbuser.setId(UUIDGenerator.getInstance()
								.getReplaceUUID());
						esgccDbuser.setPromotionId(promotionId);
						esgccDbuser.setPacketId(epas.getElectricityEnvelopeId());
						esgccDbuser.setPacketAmount(BigDecimal.valueOf(Double.valueOf(epas.getPrizes())));
						esgccDbuser.setPacketIntegral(BigDecimal.valueOf(Double.valueOf(epas.getElectricityEnvelopeIntegral())));
						esgccDbuser.setUserId(userId);
						esgccDbuser.setSource("2");
						esgccDbuser.setStatus("0");
						esgccDbuser.setLotteryRecordId(eplrListS.get(0).getLotteryRecordId());
						integralLotteryMapper.insertEsgccDbuser(esgccDbuser);
					}

				}
				else{
					result.put("rcode", "15");
					result.put("resultMsg", "该户号不在本次活动范围内");
					return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.ActivityReturnError(result)));
					//					return ResponseUtil.formatResponseByRequest(jsonpCallback, result.toString());
				}
			}
			else{
				log.info("全国抽奖===============");
				// 抽奖逻辑
				EcPromotionAwardSetting epas = getEcPromotionAwardSetting(promotionId);
				List<EcPromotionParamValue> eppvList = integralLotteryMapper.getEcPromotionParamValueList(promotionId);


				String deductedPoints = "0";//抽奖活动单次抽奖扣除积分数
				String freeTimes = "0";//每日免费抽奖次数
				for (EcPromotionParamValue eppv : eppvList) {
					if (eppv.getPromotionParamId().equals("PROM_INTEGRAL_DRAW_PRAM_00")) {
						freeTimes = eppv.getPromotionParamValue();
					} else if (eppv.getPromotionParamId().equals("PROM_INTEGRAL_DRAW_PRAM_01")) {
						deductedPoints = eppv.getPromotionParamValue();
					}
				}

				//用户当日已抽奖次数
				// 用户当日抽奖次数
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("promotionId", promotionId);
				paramMap.put("partnerId", userId);

				String userLotteryTimes = String.valueOf(integralLotteryMapper.yichoujiangcishu(paramMap).size());
				String userDeductedPoints = "0";//用户每次抽奖扣除积分数
				String koufen = "0";
				String lotteryRecordId = UUIDGenerator.getInstance().getReplaceUUID();

				//判断是否存在购物抽奖的免费机会  扣减免费机会
				BigDecimal lotteryNum = new BigDecimal("0");
				BigDecimal strTemp = new BigDecimal("0");
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("partnerId", userId);
				map.put("promotionId", promotionId);
				List<EcOrderLottery> ecOrderLotteries = ecOrderLotteryMapper.selectByPartnerId(map);
				if(ecOrderLotteries!=null&&ecOrderLotteries.size()>0){
					EcOrderLottery ecOrderLottery = ecOrderLotteries.get(0);
					lotteryNum = ecOrderLottery.getLotteryNum();
				}
				int compareTo = lotteryNum.compareTo(strTemp);
				if(compareTo==1){
					EcOrderLottery ecOrderLottery = new EcOrderLottery();
					BigDecimal countTemp = new BigDecimal(1);
					BigDecimal subtract = lotteryNum.subtract(countTemp);
					//					logger.info("countTemp==========="+countTemp);
					//					logger.info("lotteryNum==========="+lotteryNum);
					//					logger.info("subtract==========="+subtract);
					ecOrderLottery.setLotteryNum(subtract);
					ecOrderLottery.setPartnerId(userId);
					int updateByOrderId = ecOrderLotteryMapper.updateByOrderId(ecOrderLottery);
					//					logger.info("扣除购物抽奖获得的免费机会============="+updateByOrderId);
				}else{
					//用户免费抽奖次数用完时
					if (Integer.valueOf(userLotteryTimes) >= Integer.valueOf(freeTimes)) {
						boolean flag = shifoukouchujifenS(userId, promotionId);
						if (flag) {
							koufen = deductedPoints;
							JSONObject jsonObject = new JSONObject();
							jsonObject.put("ACCOUNT_NAME", param.getString("TELPHONE"));
							jsonObject.put("LOGIN_ACCOUNT_ID", userId);
							jsonObject.put("BUSINESS_ID",UUIDGenerator.getInstance().getReplaceNotMd5UUID());
							jsonObject.put("OPERATION_STATUS","01");
							jsonObject.put("EXPENDITURE_WHERE", "01");
							jsonObject.put("EXPENDITURE_DESCRIBE", "积分抽奖扣减积分");
							jsonObject.put("EXPENDITURE_NUM", koufen);
							jsonObject.put("WHEREABOUTS_ID", null);
							String resultStr=deductionIntegral(jsonObject.toString());
							log.info("调用资产中心扣减积分==================》开始《======================");
							if(resultStr.indexOf("成功") == -1){
								result.put("rcode", "14");
								result.put("resultMsg", "积分不足，抽奖失败");
								return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.ActivityReturnError(result)));
								//								return ResponseUtil.formatResponseByRequest(jsonpCallback, result.toString());
							}
						}else {
							result.put("rcode", "14");
							result.put("resultMsg", "积分不足，抽奖失败");
							return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.ActivityReturnError(result)));
							//							return ResponseUtil.formatResponseByRequest(jsonpCallback, result.toString());
						}
					}
				}

				String mianzhi = "";
				String resultMsg = "";
				// 抽中奖后
				if (!epas.getWinningType().trim().equals("2")) {
					log.info("发送短信功能暂时注释=======================》电话{}",param.getString("TELPHONE"));
					//						Map<String, String> paramMap = new LinkedHashMap<String, String>();
					//						String provinceName = iIntegralLotteryMapper.getProvinceName(provinceId);//查询网省名称
					//						String telMessage = "";
					//						String tel = integralLotteryService.getTelPhone(userId);
					//						log.info("获取的手机号===="+tel+provinceName);
					if (epas.getWinningType().trim().equals("0")) {// 积分
						resultMsg = "获得积分成功";
						//							telMessage ="【"+provinceName+"】尊敬的"+tel+"，您好，感谢您参加"+provinceName+"公司“积分抽大奖活动”,恭喜您抽中"+epas.getPrizes()+"积分，请登陆电e宝,进入积分e+查看，奖励将于三个工作日内到账。如有疑问，请致电（010-95598-1-8），感谢您对"+provinceName+"的关注！";
						Matcher mat = Pattern.compile("[\u4e00-\u9fa5]").matcher(epas.getPrizes());
						String Prizes= mat.replaceAll("").toString();
						chouzhongjiang(
								userId, promotionId,
								Prizes,lotteryRecordId);
					} else if (epas.getWinningType().trim().equals("1")) {// 礼券
						resultMsg = "获得礼券成功";
						//							telMessage ="【"+provinceName+"】尊敬的"+tel+"，您好，感谢您参加"+provinceName+"公司“积分抽大奖活动”,恭喜您抽中"+epas.getPrizes()+"元礼券，请登国网商城，进入我的商城，点击优惠券管理查看，奖励将于三个工作日内到账。如有疑问，请致电（010-95598-1-8），感谢您对"+provinceName+"的关注！";
						String code = sendCoupon(
								userId, epas.getPrizes());
						EcCouponRecord ecCouponRecord = couponMapper
								.getEcCouponRecord(code);
						mianzhi = String.valueOf(ecCouponRecord
								.getDenominationAmount());
						epas.setPrizes(mianzhi);
					} else if (epas.getWinningType().trim().equals("3")) {
						resultMsg = "获得实物成功";
						//							telMessage ="【"+provinceName+"】尊敬的"+tel+"，您好，感谢您参加"+provinceName+"公司“积分抽大奖活动”,恭喜您抽中"+epas.getPrizes()+"大奖，我们将在7-15个工作日内完成奖品发放，如有疑问，请致电（010-95598-1-8），感谢您对"+provinceName+"的关注！";
					}else if (epas.getWinningType().trim().equals("4")) {
						resultMsg = "获得电费红包成功";
						//							telMessage ="【"+provinceName+"】尊敬的"+tel+"，您好，感谢您参加"+provinceName+"公司“积分抽大奖活动”,恭喜您抽中"+epas.getPrizes()+"元小红包，请登陆电e宝,进入我的卡包查看，奖励将于三个工作日内到账。如有疑问，请致电（010-95598-1-8），感谢您对"+provinceName+"的关注！";
					}
					epas.setLotteryRecordId(lotteryRecordId);
					//						if(tel!=null && !tel.equals("")){
					//							paramMap.put(ISmsService.SMS_MOBILE, tel);
					//							paramMap.put(ISmsService.SMS_SEND_MESSAGE,
					//									java.net .URLEncoder.encode(telMessage, "utf-8"));
					//							logger.info("发送短信开始"+paramMap);
					//							iSmsEventService.sendSmsEvent(com.alibaba.fastjson.JSON.toJSONString(paramMap));
					//							logger.info("发送短信结束：[手机号"+tel);
					//						}
				}
				else{
					resultMsg = "未抽中，谢谢参与";
				}
				result.put("rcode", "10");
				result.put("resultMsg", resultMsg);
				result.put("epas", epas);

				// 增加抽奖记录
				EcPromotionLotteryRecord eplr = new EcPromotionLotteryRecord();
				eplr.setLotteryRecordId(lotteryRecordId);
				eplr.setPromotionId(promotionId);
				eplr.setLotteryAccount(userId);
				eplr.setUseIntegral(Double.valueOf(userDeductedPoints));
				eplr.setWinningType(epas.getWinningType().trim());
				eplr.setPrizes(epas.getPrizes());
				eplr.setWinningPrice("");
				eplr.setStates("");
				if (epas.getWinningType().trim().equals("0")) {//积分
					Double ss= Double.valueOf(epas.getPrizes())*0.005;
					eplr.setWinningPrice(String.valueOf(ss));
				}
				if (epas.getWinningType().trim().equals("1")) {//礼券
					eplr.setPrizes(mianzhi);
					eplr.setWinningPrice(mianzhi);
				}
				if (epas.getWinningType().trim().equals("4")) {//电费红包
					eplr.setStates("1");//派发中
				}
				eplr.setAwardSettingId(epas.getAwardSettingId());
				eplr.setLotteryTime(new Date());
				eplr.setLotterySourec("3");
				log.info("添加抽奖记录==================》开始《=================");
				integralLotteryMapper.insertEcPromotionLotteryRecord(eplr);
				log.info("添加抽奖记录==================》结束《=================");

				if (epas.getWinningType().trim().equals("4")) {// 电费红包
					Map<String, Object> paramMap1 = new HashMap<String, Object>();
					paramMap1.put("promotionId", promotionId);
					paramMap1.put("partnerId", userId);
					List<EcPromotionLotteryRecord> eplrListS = integralLotteryMapper
							.yichoujiangcishu(paramMap1);
					EsgccDbuser esgccDbuser=new EsgccDbuser();
					esgccDbuser.setId(UUIDGenerator.getInstance()
							.getReplaceUUID());
					esgccDbuser.setPromotionId(promotionId);
					esgccDbuser.setPacketId(epas.getElectricityEnvelopeId());
					esgccDbuser.setPacketAmount(BigDecimal.valueOf(Double.valueOf(epas.getPrizes())));
					esgccDbuser.setPacketIntegral(BigDecimal.valueOf(Double.valueOf(epas.getElectricityEnvelopeIntegral())));
					esgccDbuser.setUserId(userId);
					esgccDbuser.setSource("2");
					esgccDbuser.setStatus("0");
					esgccDbuser.setLotteryRecordId(eplrListS.get(0).getLotteryRecordId());
					integralLotteryMapper.insertEsgccDbuser(esgccDbuser);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("rcode", "1");
			result.put("resultMsg", "接口访问失败");
		}
		return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.ActivityReturnSucceed(result)));
		//		return ResponseUtil.formatResponseByRequest(jsonpCallback, result.toString());
	}
	/**
	 * 我的中奖记录
	 * 
	 * @param token
	 * @param jsonpCallback
	 * @param jsonStr
	 * @return
	 */
	@Override
	public JSONObject getMyLotterySuccessInfo(JSONObject params) {
		log.info("我的中奖记录查询开始："+ params);
		JSONObject result = new JSONObject();
		//			String userId = TokenUtil.getInstance(redisManager).getUserIdByToken(token);
		String userId = params.getString("UNION_ID");
		if (StringUtils.isBlank(userId)) {
			result.put("rcode", "1204");
			result.put("resultMsg", "用户未登陆");
		} else {

			result.put("userId", userId);
			log.info("解析开始：curPage"+ params.getString("CURPAGE"));
			log.info("解析开始：pageSize"+ params.getString("PAGESIZE"));

			try {
				//获取奖品邮寄地址
				List<EcConsignee> myConsignees = ecConsigneeUcExtMapper.selectByMemberId(userId);
				Map<String,String> addressMap = new HashMap<String,String>();
				if (myConsignees != null && !myConsignees.isEmpty()) {
					addressMap.put("consigneeName", myConsignees.get(0).getConsigneeName());
					addressMap.put("phone", myConsignees.get(0).getConsigneeMobile());
					addressMap.put("address", myConsignees.get(0).getConsigneeDetailAddress());
				}

				//获取我的中奖记录
				//					Page page = LocalPageContext.setPageViaRequest(param.getString("curPage"), Integer.parseInt(param.getString("pageSize")));
				long pageSize = params.getLong("PAGESIZE");
				long page = params.getLong("CURPAGE");
				JSONObject resultJson=new JSONObject();
				PageVo<SignDetail> pageVo = new PageVo<SignDetail>();
				pageVo.setPAGE_SIZE(pageSize);
				pageVo.setCUR_PAGE(page);
				Map<String, String> map1=new HashMap<>();


				Map<String, Object> param = new HashMap<String, Object>();
				param.put("userId", userId);
				param.put("pageSize", pageVo.getPAGE_SIZE());
				param.put("curPosition", pageVo.getSTART());
				List<EcPromotionLotteryRecord> pslrList = ecPromotionLotteryRecordMapper.getEcPromotionLotteryRecordList(param);

				//获取中奖信息
				List<Map<String, String>> recordMap = new ArrayList<Map<String, String>>();
				log.info("中奖纪录：" + pslrList);
				if (pslrList != null && !pslrList.isEmpty()) {
					EcPromotionAwardSetting prize = new EcPromotionAwardSetting();//奖品信息
					String imgUrl = "";//奖品图片url
					for (EcPromotionLotteryRecord record : pslrList) {
						log.info("活动ID：" + record.getPromotionId());
						log.info("奖品ID：" + record.getAwardSettingId());
						//获取奖品信息
						List<EcPromotionAwardSetting> epasList = integralLotteryMapper.getEcPromotionAwardSettingList(record.getPromotionId());
						//							logger.info("奖品查询开始：" + epasList);
						if (epasList != null && !epasList.isEmpty() && StringUtils.isNotBlank(record.getAwardSettingId())) {
							for (EcPromotionAwardSetting epas : epasList) {
								if (StringUtils.equals(record.getAwardSettingId(), epas.getAwardSettingId())) {
									prize = epas;
									break;
								}
							}
						}

						imgUrl = getImgUrl(prize.getImgID());
						Map<String, String> map = new HashMap<String, String>();

						map.put("lotteryDate", TimeUtil.getDateFomat(record.getLotteryTime(), "yyyy-MM-dd HH:mm:ss"));
						map.put("promotionName", record.getPromotionName());
						map.put("prize", record.getPrizes());
						map.put("winningType", record.getWinningType());
						map.put("prizeStatus", record.getStates());
						map.put("prizeImg", imgUrl);
						recordMap.add(map);
					}
				}

				result.put("addressMap", addressMap);//奖品邮寄地址
				result.put("recordInfo", recordMap);//中奖信息
				//				result.put("totalSize", page.getTotalRows());
				result.put("rcode", "0");
				result.put("resultMsg", "接口调用成功");
			} catch (Exception e) {
				e.printStackTrace();
				result.put("rcode", "1");
				result.put("resultMsg", "接口访问失败");
			}
		}
		return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.ActivityReturnSucceed(result)));
		//			return ResponseUtil.formatResponseByRequest(jsonpCallback, result.toString());

	}

	/**
	 * 验证是否有可扣除的积分数
	 * @param userId
	 * @param promotionId
	 * @return
	 */
	public boolean shifoukouchujifenS(String userId, String promotionId) {
		boolean flag = true;
		//积分账户余额查询
		String ACCOUNT_QUERY_URL = urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.ACCOUNT_INTEGRAL_QUERY.getKey());
		List<EcPromotionParamValue> eppvList = integralLotteryMapper.getEcPromotionParamValueList(promotionId);
		String kcfs = "0";
		for (EcPromotionParamValue eppv : eppvList) {
			if (eppv.getPromotionParamId().equals("PROM_INTEGRAL_DRAW_PRAM_01")) {
				kcfs = eppv.getPromotionParamValue();
			}
		}
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("LOGIN_ACCOUNT_ID", userId);
		jsonObject.put("IP","192.0.0.1");
//		headerMap.put("CHANNEL_RESOURCE",json.getString("CHANNEL_NO"));//渠道编码
		jsonObject.put("CHANNEL_RESOURCE","5");//渠道编码
		jsonObject.put("USER_NAME","网上国网");//
		String resultJson = RequestUtils.sendPost(ACCOUNT_QUERY_URL, jsonObject.toString());
		//		Integer bpValue = iEcIntegralDetailService.getAvailabelIntegralById(userId);
		JSONObject returnjson=JSONObject.parseObject(resultJson);
		//		JSONObject returnjson=new JSONObject();
		//		returnjson.put("rcode", "0");
		//		returnjson.put("content", "{'ENABLE_NUMBER':'100000'}");

		if (returnjson.get("rcode").equals("0")) {
			log.info("验证是否有可扣除的积分数===================================>returnjson={}",returnjson);
			log.info("验证是否有可扣除的积分数===================================>kcfs={}",kcfs);
			log.info("验证是否有可扣除的积分数===================================>BALANCE={}",returnjson.getJSONObject("content").getString("BALANCE"));
			if (Integer.parseInt(returnjson.getJSONObject("content").getString("BALANCE"))<Integer.parseInt(kcfs)) {
				flag = false;
			}

		}

		return flag;
	}
	/**
	 * 全省抽奖规则
	 * @param promotionId
	 * @return
	 */
	public EcPromotionAwardSetting getEcPromotionAwardSetting(String promotionId) {

		// 4.得到（每日免费抽奖次数，单次抽奖积分扣除数，积分投入数）
		List<EcPromotionParamValue> eppvList = integralLotteryMapper
				.getEcPromotionParamValueList(promotionId);
		String promotionParamValue = "";
		for (EcPromotionParamValue eppv : eppvList) {
			if (eppv.getPromotionParamId().equals("PROM_INTEGRAL_DRAW_PRAM_02")) {
				promotionParamValue = eppv.getPromotionParamValue();
			}
		}

		List<EcPromotionAwardSetting> epasList = integralLotteryMapper
				.getEcPromotionAwardSettingList(promotionId);

		int size = epasList.size();
		List<Double> orignalRates = new ArrayList<Double>(size);
		log.info("奖池promotionParamValue=============="+promotionParamValue);
		for (EcPromotionAwardSetting epasS : epasList) {
			Double gailv = 0d;
			if (epasS.getWinningType().trim().equals("0")){
				if (Integer.valueOf(epasS.getPrizes()) > Integer.valueOf(promotionParamValue)) {
					gailv = 0d;
				}
				else gailv = epasS.getWinningProbabilityChange() / 100;
			}
			else if (epasS.getWinningType().trim().equals("4")){// 中奖后类型为电费红包判断是否有多余积分
				if (Integer.valueOf(epasS.getElectricityEnvelopeIntegral()) > Integer.valueOf(promotionParamValue)) {
					gailv = 0d;
				}
				else gailv = epasS.getWinningProbabilityChange() / 100;
			}
			else gailv = epasS.getWinningProbabilityChange() / 100;
			orignalRates.add(gailv);
		}
		// 计算总权重，这样可以保证不一定总权重是1
		double sumRate = 0d;
		for (double rate : orignalRates) {
			sumRate += rate;
		}

		// 计算每个物品在总权重的基础下的概率情况[0-1的概率区间]
		List<Double> sortOrignalRates = new ArrayList<Double>(size);
		Double tempSumRate = 0d;
		for (double rate : orignalRates) {
			tempSumRate += rate;
			sortOrignalRates.add(tempSumRate / sumRate);
		}
		//		logger.info("抽中奖品的GAILV分布=============="+sortOrignalRates);
		// 算法分析:根据概率将奖品划分区间，每个区间代表一个奖品，然后抽取随机数，反查落在那个区间上，即为所抽取的奖品。
		double nextDouble = Math.random();
		log.info("随机数=============="+nextDouble);
		sortOrignalRates.add(nextDouble);
		Collections.sort(sortOrignalRates);
		int awardIndex = sortOrignalRates.indexOf(nextDouble);// 抽中的奖代码索引，索引从0开始
		//		logger.info("抽中奖品序号=============="+awardIndex);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("promotionId", promotionId);
		paramMap.put("awardIndex", awardIndex);

		EcPromotionAwardSetting epas = new EcPromotionAwardSetting();
		epas = integralLotteryMapper.getEcPromotionAwardSetting(paramMap);



		if (!(epas.getWinningType().trim()).equals("2")) {
			if (epas.getWinningType().trim().equals("0")) {// 中奖后类型为积分判断是否有多余积分
				// 去除中文
				Matcher mat = Pattern.compile("[\u4e00-\u9fa5]").matcher(epas.getPrizes());
				String prizes = mat.replaceAll("");
				if (Integer.valueOf(prizes) > Integer
						.valueOf(promotionParamValue)) {
					epas.setWinningType("2");
					epas.setPrizes("0");
				}
			}
			else if (epas.getWinningType().trim().equals("1")) {
				EcCouponRecord ecCouponRecord = this
						.getCouponsRecordByPromotionId(epas.getPrizes());// 获取一条可以领的礼券明细
				if (ecCouponRecord == null) {
					epas.setWinningType("2");
					epas.setPrizes("0");
				}
			}
			else if (epas.getWinningType().trim().equals("4")) {// 中奖后类型为电费红包判断是否有多余积分
				if (Integer.valueOf(epas.getElectricityEnvelopeIntegral()) > Integer
						.valueOf(promotionParamValue)) {
					epas.setWinningType("2");
					epas.setPrizes("0");
				}
			}
		}

		//修改概率*******************************************************************
		if(!(epas.getWinningType().trim()).equals("2")){
			if((epas.getStockAmt()-1)==0){
				Double gailv=0.0;
				epas.setWinningProbabilityChange(gailv);
			}
			/*else{
				gailv=epas.getWinningProbabilityChange()*((Double.valueOf(String.valueOf(epas.getStockAmt()))-1)/Double.valueOf(String.valueOf(epas.getSendAmt())));

			}*/


			epas.setStockAmt(Integer.valueOf(String.valueOf(epas.getStockAmt() - 1)));

			//修改奖品概率
			storeDrawMapperK.updateEcPromotionAwardSetting(epas);

		}

		return epas;
	}
	/**
	 * 地市范围抽奖
	 * @param promotionId
	 * @param cityId
	 * @return
	 */
	public EcPromotionAwardSetting getEcPromotionAwardSettingCity(String promotionId, String cityId) {

		// 4.得到（每日免费抽奖次数，单次抽奖积分扣除数，积分投入数）
		List<EcPromotionParamValue> eppvList = integralLotteryMapper
				.getEcPromotionParamValueList(promotionId);
		String promotionParamValue = "0";
		for (EcPromotionParamValue eppv : eppvList) {
			if (eppv.getPromotionParamId().equals("PROM_INTEGRAL_DRAW_PRAM_02")) {
				promotionParamValue = eppv.getPromotionParamValue();
			}
		}

		log.info("奖池积分数========"+promotionParamValue);
		Map<String, String> param = new HashMap<String, String>();
		param.put("promotionId",promotionId);
		param.put("cityId",cityId);

		List<EcPromotionAwardSetting> epasList = integralLotteryMapper
				.getEcPromotionAwardSettingListCity(param);
		//		logger.info("地市奖品列表epasList========"+epasList);
		int size = epasList.size();
		List<Double> orignalRates = new ArrayList<Double>(size);

		log.info("奖品概率=============》");
		for (EcPromotionAwardSetting epasS : epasList) {
			Double gailv = 0d;
			if (epasS.getWinningType().trim().equals("0")){
				log.info("奖品概率=============》111111111111");
				// 去除中文
				Matcher mat = Pattern.compile("[\u4e00-\u9fa5]").matcher(epasS.getPrizes());
				epasS.setPrizes(mat.replaceAll(""));
				if (Integer.valueOf(epasS.getPrizes()) > Integer.valueOf(promotionParamValue)) {
					log.info("奖品概率=============》222222222222");
					gailv = 0d;
				}
				else gailv = epasS.getWinningProbabilityChange() / 100;	log.info("奖品概率=============》33333333333333");

			}
			else if (epasS.getWinningType().trim().equals("4")){// 中奖后类型为电费红包判断是否有多余积分
				log.info("奖品概率=============》444444444444444");
				if (Integer.valueOf(epasS.getElectricityEnvelopeIntegral()) > Integer.valueOf(promotionParamValue)) {
					log.info("奖品概率=============》5555555555555555");
					gailv = 0d;
				}
				else gailv = epasS.getWinningProbabilityChange() / 100;	log.info("奖品概率=============》6666666666666");
			}
			else gailv = epasS.getWinningProbabilityChange() / 100;	log.info("奖品概率=============》77777777777777777");
			log.info("++++++++++++++++++++++++++++++++++"+gailv);
			orignalRates.add(gailv);
		}
		// 计算总权重，这样可以保证不一定总权重是1
		double sumRate = 0d;
		for (double rate : orignalRates) {
			sumRate += rate;
		}

		// 计算每个物品在总权重的基础下的概率情况[0-1的概率区间]
		List<Double> sortOrignalRates = new ArrayList<Double>(size);
		Double tempSumRate = 0d;
		for (double rate : orignalRates) {
			tempSumRate += rate;
			sortOrignalRates.add(tempSumRate / sumRate);
		}
		log.info("抽奖概率分布========"+sortOrignalRates);
		// 算法分析:根据概率将奖品划分区间，每个区间代表一个奖品，然后抽取随机数，反查落在那个区间上，即为所抽取的奖品。
		double nextDouble = Math.random();
		sortOrignalRates.add(nextDouble);
		Collections.sort(sortOrignalRates);
		int awardIndex = sortOrignalRates.indexOf(nextDouble);// 抽中的奖代码索引，索引从0开始
		//		logger.info("地市奖品列表索引========"+awardIndex);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("promotionId", promotionId);
		paramMap.put("awardIndex", awardIndex);
		paramMap.put("cityId", cityId);

		EcPromotionAwardSetting epas = new EcPromotionAwardSetting();
		epas = integralLotteryMapper.getEcPromotionAwardSettingCity(paramMap);

		// 去除中文
		Matcher mat = Pattern.compile("[\u4e00-\u9fa5]").matcher(epas.getPrizes());
		String prizes = mat.replaceAll("");

		if (!(epas.getWinningType().trim()).equals("2")) {
			if (epas.getWinningType().trim().equals("0")) {// 中奖后类型为积分判断是否有多余积分
				if (Integer.valueOf(prizes) > Integer
						.valueOf(promotionParamValue)) {
					epas.setWinningType("2");
					epas.setPrizes("0");
				}
			} else if (epas.getWinningType().trim().equals("1")) {
				EcCouponRecord ecCouponRecord = this
						.getCouponsRecordByPromotionId(epas.getPrizes());// 获取一条可以领的礼券明细
				if (ecCouponRecord == null) {
					epas.setWinningType("2");
					epas.setPrizes("0");
				}
			}
			else if (epas.getWinningType().trim().equals("4")) {// 中奖后类型为电费红包判断是否有多余积分
				if (Integer.valueOf(epas.getElectricityEnvelopeIntegral()) > Integer
						.valueOf(promotionParamValue)) {
					epas.setWinningType("2");
					epas.setPrizes("0");
				}
			}
		}

		//修改概率*******************************************************************
		if(!(epas.getWinningType().trim()).equals("2")){
			if((epas.getStockAmt()-1)==0){
				Double gailv=0.0;
				epas.setWinningProbabilityChange(gailv);
			}
			epas.setStockAmt(Integer.valueOf(String.valueOf(epas.getStockAmt() - 1)));

			//修改奖品库存
			storeDrawMapperK.updateEcPromotionAwardSetting(epas);
		}

		return epas;
	}
	// 礼券************************************************************
	/**
	 * 获取一条可以领的礼券明细
	 *
	 * @param promotionId
	 *            礼券活动编号
	 * @return EcCouponRecord 礼券明细实体
	 */
	public EcCouponRecord getCouponsRecordByPromotionId(String promotionId) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
		String date =df.format(new Date());
		List<EcCouponRecord> couponsList = this
				.findCouponsBypromotionsId(promotionId);
		EcCouponRecord ecCouponRecord = null;
		if (CollectionUtils.isNotEmpty(couponsList)) {
			long index =redisTem.llen(RedisKey.GIFT_CERTIFICATE_PREFIXX.getKey()+date+"_"+promotionId)-1;
			log.info("获取couponsListlist=================》长度{}",index);
			// 如果游标数大于礼券集合数 则删除改礼券缓存 ，重新从数据库获取礼券加入缓存中
			if (index >= couponsList.size()) {
				redisTem.lpop(RedisKey.GIFT_CERTIFICATE_PREFIXX.getKey()+date+"_"+promotionId);
				// 重新初始化礼券缓存数据
				couponsList = this.findCouponsBypromotionsId(promotionId);
				redisTem.setByte(RedisKey.GIFT_CERTIFICATE_PREFIXX.getKey(), date+"_"+promotionId,SerializeUtil.serialize(couponsList));
				index = redisTem.llen(RedisKey.GIFT_CERTIFICATE_PREFIXX.getKey()+date+"_"+promotionId)-1;
				if (CollectionUtils.isEmpty(couponsList)) {
					// logger.debug(promotionId+"礼券活动的礼券已领完");
					return null;
				}
			}
			ecCouponRecord = couponsList.get((int)index);
		}
		return ecCouponRecord;
	}

	/**
	 * 初始化1000条可用优惠券放入缓存
	 *
	 * @param promotionId
	 *            礼券活动编号
	 * @return List<EcCouponRecord> 礼券明细集合
	 */
	public List<EcCouponRecord> findCouponsBypromotionsId(String promotionId) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
		String date =df.format(new Date());
		//redis读取序列化对象
		byte[] unReceivedCouponListin = redisTem.getByte(RedisKey.GIFT_CERTIFICATE_PREFIXX.getKey(),date+"_"+promotionId);
		//反序列序列化对象
		List<EcCouponRecord> unReceivedCouponList=SerializeUtil.unserializeForList(unReceivedCouponListin);
		if (CollectionUtils.isEmpty(unReceivedCouponList)) {
			try {
				unReceivedCouponList = couponMapper
						.getUnReceivedCouponByOneThousand(promotionId);
				//redis保存序列化对象
				redisTem.setByte(RedisKey.GIFT_CERTIFICATE_PREFIXX.getKey(), date+"_"+promotionId,SerializeUtil.serialize(unReceivedCouponList));
				if (CollectionUtils.isEmpty(unReceivedCouponList)) {
					return unReceivedCouponList;
				}
			} catch (Exception e) {
				// logger.info("", e);
			}
		}
		return unReceivedCouponList;
	}
	/**
	 * 获取图片路径
	 * @param prize
	 * @param imgUrl
	 * @return
	 */
	private String getImgUrl(String imgId) {
		String imgUrl = "";
		Fileinfo fileInfoList = fileinfoMapper.selectByBuzId(imgId).get(0);
		String IMG_URL = urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.IMG_URLADD.getKey());// "http://images.esgmallt.com";//
		if (fileInfoList != null ) {
			imgUrl = IMG_URL + fileInfoList.getRelapath() + fileInfoList.getFileaname();
		}
		return imgUrl;
	}
	/**
	 * 账户中心扣减接口
	 * @param jsonstr
	 * @return
	 */
	private String deductionIntegral(String jsonstr) {
		String ACCOUNT_INTEGRAL_DEDUCTION = urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.ACCOUNT_INTEGRAL_DEDUCTION.getKey());
		//			JSONObject jsonObject = new JSONObject();
		//			jsonObject.put("ACCOUNT_NAME", PROVINCE_CODE);
		//			jsonObject.put("LOGIN_ACCOUNT_ID", ACCOUNT_MAIN_ID);
		//			jsonObject.put("BUSINESS_ID", ORG_NO);
		//			jsonObject.put("OPERATION_STATUS", POWER_USER_NO);
		//			jsonObject.put("EXPENDITURE_WHERE", INCOME_SOURCE);
		//			jsonObject.put("EXPENDITURE_DESCRIBE", INCOME_TYPE);
		//			jsonObject.put("EXPENDITURE_NUM", INCOME_NUM);
		//			jsonObject.put("WHEREABOUTS_ID", new Date());
		JSONObject jsonObject =JSONObject.parseObject(jsonstr);
		jsonObject.put("IP","192.0.0.1");
//		headerMap.put("CHANNEL_RESOURCE",json.getString("CHANNEL_NO"));//渠道编码
		jsonObject.put("CHANNEL_RESOURCE","5");//渠道编码
		jsonObject.put("USER_NAME","网上国网");//
		log.info("扣减入参==================》"+jsonObject.toJSONString());
		log.info("添加入参地址==================》"+ACCOUNT_INTEGRAL_DEDUCTION);
		String jsonQueryResult = RequestUtils.sendPost(ACCOUNT_INTEGRAL_DEDUCTION, jsonObject.toJSONString());
		return jsonQueryResult;

	}
	/**
	 *  账户中心添加接口
	 * @param jsonstr
	 * @return
	 */
	private String addIntegral(String jsonstr) {
		String ACCOUNT_INTEGRAL_ADD = urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.ACCOUNT_INTEGRAL_ADD.getKey());
		//			JSONObject jsonObject = new JSONObject();
		//			jsonObject.put("ACCOUNT_NAME", PROVINCE_CODE);
		//			jsonObject.put("LOGIN_ACCOUNT_ID", ACCOUNT_MAIN_ID);
		//			jsonObject.put("BUSINESS_ID", ORG_NO);
		//			jsonObject.put("OPERATION_STATUS", POWER_USER_NO);
		//			jsonObject.put("EXPENDITURE_WHERE", INCOME_SOURCE);
		//			jsonObject.put("EXPENDITURE_DESCRIBE", INCOME_TYPE);
		//			jsonObject.put("EXPENDITURE_NUM", INCOME_NUM);
		//			jsonObject.put("WHEREABOUTS_ID", new Date());
		JSONObject jsonObject =JSONObject.parseObject(jsonstr);
		jsonObject.put("IP","192.0.0.1");
//		headerMap.put("CHANNEL_RESOURCE",json.getString("CHANNEL_NO"));//渠道编码
		jsonObject.put("CHANNEL_RESOURCE","5");//渠道编码
		jsonObject.put("USER_NAME","网上国网");//
		log.info("添加入参==================》"+jsonObject.toJSONString());
		log.info("添加入参地址==================》"+ACCOUNT_INTEGRAL_ADD);
		String jsonQueryResult = RequestUtils.sendPost(ACCOUNT_INTEGRAL_ADD, jsonObject.toJSONString());
		return jsonQueryResult;

	}

	/**
	 * 积分中奖后修改数据
	 * @param userId
	 * @param promotionId
	 * @param prizes
	 * @param lotteryRecordId
	 */
	public void chouzhongjiang(String userId, String promotionId, String prizes, String lotteryRecordId) {
		// 4.得到（每日免费抽奖次数，单次抽奖积分扣除数，积分投入数）
		List<EcPromotionParamValue> eppvList = integralLotteryMapper
				.getEcPromotionParamValueList(promotionId);
		String promotionParamValue = "";
		for (EcPromotionParamValue eppv : eppvList) {
			if (eppv.getPromotionParamId().equals("PROM_INTEGRAL_DRAW_PRAM_02")) {
				promotionParamValue = eppv.getPromotionParamValue();
			}
		}
		// 重置奖池
		EcPromotionParamValue eppv = new EcPromotionParamValue();
		eppv.setPromotionParamId("PROM_INTEGRAL_DRAW_PRAM_02");
		eppv.setPromotionParamValue(String.valueOf(Integer
				.valueOf(promotionParamValue) - Integer.valueOf(prizes)));
		eppv.setPromotionId(promotionId);
		integralLotteryMapper.updateEcPromotionParamValue(eppv);

		Calendar ca = Calendar.getInstance();
		// 今年
		int year = ca.get(Calendar.YEAR);
		try {
			JSONObject jsonObject=new JSONObject();
			jsonObject.put("LOGIN_ACCOUNT_ID", userId);
			jsonObject.put("BUSINESS_ID", UUIDGenerator.getInstance().getReplaceNotMd5UUID());
			jsonObject.put("INCOME_SOURCE", "05");
			jsonObject.put("OPERATION_STATUS", "02");
			jsonObject.put("SOURCE_DESCRIBE", "抽奖赠送积分");
			jsonObject.put("INCOME_NUM", Integer.valueOf(prizes));
			String resultStr=addIntegral(jsonObject.toString());
			//			String resultStr =ecIntegralDetailServiceImpl.changeIntegralAndGlobalLock(isPresent,userMap,sourceMap);
			if(resultStr.indexOf("成功")>-1){
				log.info("=======积分抽奖中积分-赠送积分成功："+resultStr+"========");
			}else{
				log.info("=======积分抽奖中积分-赠送积分失败："+resultStr+"========");
				throw new RuntimeException();
			}
		} catch (Exception e) {
			log.info("=======积分抽奖中积分-赠送积分是否成功：赠送异常========");
			e.printStackTrace();
		}


	}
	/**
	 * 领取礼券 直接关联ecCouponRecord表领取礼券 与批次无关
	 * 
	 * @param userId
	 *            用户ID
	 * @param promotionId
	 *            礼券活动编号
	 * @return String 领取成功返回礼券明细编号，否则为 null
	 */
	public String sendCoupon(String userId, String promotionId) {
		String flag = null;
		EcCouponRecord ecCouponRecord = this
				.getCouponsRecordByPromotionId(promotionId);
		if (ecCouponRecord != null) {
			String couponId = ecCouponRecord.getCouponId();
			Map<String, String> param = new HashMap<String, String>();
			param.put("status", "02");
			param.put("userId", userId);
			param.put("couponId", couponId);
			couponMapper.updateCouponRecord(param);
			flag = couponId;
		} else {
		}
		return flag;
	}

}
